/* eslint-disable */
import React, { PureComponent } from 'react';
import { Card, Row, Col, Button } from 'antd';

// tips: 参考图解：http://www.jianshu.com/p/12a5e6b0fa39
// 1. 冒泡排序;
function bubbleSort(arr) {
  const len = arr.length;
  for (var i = 0; i < len; i++) {
    for (var j = 0; j < len - 1 - i; j++) {
      if (arr[j] > arr[j+1]) { //相邻元素两两对比
        var temp = arr[j+1]; //元素交换
        arr[j+1] = arr[j];
        arr[j] = temp;
      }
    }
  }
  return arr;
}

// 2. 选择排序
function selectionSort(arr) {
  var len = arr.length;
  var minIndex, temp;
  for (var i = 0; i < len - 1; i++) {
    minIndex = i;
    for (var j = i + 1; j < len; j++) {
      if (arr[j] < arr[minIndex]) { //寻找最小的数
        minIndex = j; // 将最小数的索引保存
      }
    }
    temp = arr[i];
    arr[i] = arr[minIndex];
    arr[minIndex] = temp;
  }
  return arr;
}

export default class Demo2 extends PureComponent {
  handleDemo1 = () => {
    console.log('冒泡排序')
    console.time()
    const array = [1, 23, 15, 6, 19, 112, 8, 3];
    bubbleSort(array);
    console.log(array);
    console.timeEnd()
  }
  handleDemo2 = () => {
    console.log('选择排序')
    console.time()
    const array = [1, 23, 15, 6, 19, 112, 8, 3];
    selectionSort(array);
    console.log(array);
    console.timeEnd()
  }
  render() {
    return (
      <Row>
        <Col>
          <Card title="测试">
            <h4>1. 冒泡排序</h4>
            <Button type="primary" onClick={this.handleDemo1}>冒泡排序</Button>
            <h4>2. 选择排序</h4>
            <Button type="primary" onClick={this.handleDemo2}>选择排序</Button>
          </Card>
        </Col>
      </Row>
    );
  }
}
